package cn.xmut.gulimall.product.service.impl;

import cn.xmut.common.utils.PageUtils;
import cn.xmut.common.utils.Query;
import cn.xmut.gulimall.product.dao.CategoryDao;
import cn.xmut.gulimall.product.entity.CategoryEntity;
import cn.xmut.gulimall.product.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查出所有分类以及子分类 ，以树形结构组装起来
     *
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //2.组装成父子的树形结构
        //2.1找到所有的一级分类
        List<CategoryEntity> level1Menu = entities.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .peek(menu -> menu.setChildren(getChildren(menu, entities)))
                .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());

        return level1Menu;
    }


    /**
     * 批量删除菜单
     * @param ids
     * @return
     */
    @Override
    public boolean removeMenuByIds(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)){
            return false;
        }
        //TODO 检查当前删除的菜单是否被别的地方引用

        return SqlHelper.retBool(baseMapper.deleteBatchIds(ids));
    }

    /**
     * 递归查找所有菜单的子菜单
     *
     * @param currentCategory
     * @param list
     * @return
     */
    private List<CategoryEntity> getChildren(CategoryEntity currentCategory, List<CategoryEntity> list) {
        //1.从所有的菜单中找出父菜单是当前菜单的节点(当前菜单currentCategory下所有的子菜单节点)；
        //  再通过map映射，递归设置当前菜单的所有子菜单；将结果进行排序；最后转成集合汇总。
        return list.stream().filter(categoryEntity -> categoryEntity.getParentCid().equals(currentCategory.getCatId()))
                .peek(categoryEntity -> categoryEntity.setChildren(getChildren(categoryEntity, list)))
                .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());
    }

}